﻿package net.wangit.dev;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.User;
import net.wangit.context.ActionContext;
import net.wangit.jdbc.ColumnRow;
import net.wangit.user.ProjectManager;
import net.wangit.util.Checker;

public class LockUtil {

	private static final String IMG_ELMENT_ID = "lockstatus";
	private static final String OLD_LOCK_ELMENT_ID = "oldlock";

	public LockUtil() {
	}

	public static void setElements(ActionContext ac, Unit unit,
			Object[][] actions) {
		boolean lock = false;
		MapList data = unit.getData();
		if (!Checker.isEmpty(data))
			lock = "1".equals(data.getRow(0).get("l"));
		Element element = unit.getElement(LockUtil.IMG_ELMENT_ID);
		if (lock) {
			StringBuffer html = new StringBuffer("<span class=lock");
			String locker = data.getRow(0).get("ler");
			User user = ac.getVisitor().getUser();
			if (!user.getId().equals(locker)
					&& !(user instanceof ProjectManager))
				removeActions(actions);
			else
				html.append(" onclick=lock(this,'").append(unit.getId())
						.append("')");
			html.append("></span><span class=locker>(by ").append(locker)
					.append(")</span>");
			element.setCustom(html.toString());
		} else {
			element.setCustom((new StringBuilder(
					"<span class=unlock onclick=lock(this,'")).append(
					unit.getId()).append("')></span>").toString());
		}
	}

	private static void removeActions(Object actions[][]) {
		for (int i = 0; i < actions.length; i++) {
			Unit unit = (Unit) actions[i][0];
			for (int j = 1; j < actions[i].length; j++)
				unit.removeElement((String) actions[i][j]);

		}

	}

	public static void setFields(ActionContext ac, ColumnRow row,
			String oldLockUnitId) {
		String newLock = row.get("l");
		String oldLock = ac.getRequestParameter((new StringBuilder(String
				.valueOf(oldLockUnitId))).append(".").append(
				LockUtil.OLD_LOCK_ELMENT_ID).toString(), "0");
		if (!oldLock.equals(newLock))
			if ("1".equals(newLock)) {
				row.set("l", "1");
				row.set("ler", ac.getVisitor().getUser().getId());
			} else {
				row.set("l", "0");
			}
	}
}
